import 'package:flutter/material.dart';
import '../models/morse_character.dart';
import '../services/morse_audio_service.dart';

class LearnPage extends StatefulWidget {
  const LearnPage({super.key});

  @override
  State<LearnPage> createState() => _LearnPageState();
}

class _LearnPageState extends State<LearnPage> with TickerProviderStateMixin {
  late AnimationController _animationController;
  late List<AnimationController> _elementAnimationControllers;
  late List<Animation<double>> _elementAnimations;
  final MorseAudioService _audioService = MorseAudioService();
  
  bool _isPlaying = false;
  bool _hasPlayedOnce = false;
  int _currentIndex = 0;
  final int _totalLevels = 36;

  MorseCharacter get currentCharacter => MorseData.characters[_currentIndex];

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    
    _elementAnimationControllers = [];
    _elementAnimations = [];
    _initializeElementAnimations();
  }

  void _initializeElementAnimations() {
    // 清理旧的动画控制器
    for (var controller in _elementAnimationControllers) {
      controller.dispose();
    }

    final elements = currentCharacter.elements;
    _elementAnimationControllers = List.generate(
      elements.length,
      (index) => AnimationController(
        duration: Duration(milliseconds: elements[index] == MorseElement.dot ? 200 : 600),
        vsync: this,
      ),
    );

    _elementAnimations = _elementAnimationControllers.map((controller) {
      return Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(parent: controller, curve: Curves.easeInOut),
      );
    }).toList();
  }

  @override
  void dispose() {
    _animationController.dispose();
    for (var controller in _elementAnimationControllers) {
      controller.dispose();
    }
    _audioService.stop();
    super.dispose();
  }

  Future<void> _playMorseCode() async {
    if (_isPlaying) return;

    setState(() {
      _isPlaying = true;
    });

    try {
      // 同时播放音频和动画
      final audioFuture = _audioService.playCharacter(currentCharacter);
      final animationFuture = _playAnimationSequence();
      
      await Future.wait([audioFuture, animationFuture]);
    } finally {
      setState(() {
        _isPlaying = false;
        _hasPlayedOnce = true;
      });
    }
  }

  Future<void> _playAnimationSequence() async {
    // 播放摩尔斯电码动画序列
    for (int i = 0; i < _elementAnimationControllers.length; i++) {
      final element = currentCharacter.elements[i];
      await _elementAnimationControllers[i].forward();
      
      // 根据摩尔斯元素类型添加相应的延迟
      if (element == MorseElement.dot) {
        await Future.delayed(const Duration(milliseconds: 200)); // 点的持续时间
      } else {
        await Future.delayed(const Duration(milliseconds: 600)); // 线的持续时间
      }
      
      // 元素间隔
      if (i < _elementAnimationControllers.length - 1) {
        await Future.delayed(const Duration(milliseconds: 100));
      }
    }
  }

  void _goToPrevious() {
    if (_currentIndex > 0) {
      setState(() {
        _currentIndex--;
        _hasPlayedOnce = false;
      });
      _resetAnimations();
      _initializeElementAnimations();
    }
  }

  void _goToNext() {
    if (_currentIndex < MorseData.characters.length - 1) {
      setState(() {
        _currentIndex++;
        _hasPlayedOnce = false;
      });
      _resetAnimations();
      _initializeElementAnimations();
    }
  }

  void _resetAnimations() {
    for (var controller in _elementAnimationControllers) {
      controller.reset();
    }
  }

  void _markAsMastered() {
    // 实现标记为已掌握的逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Character ${currentCharacter.character} marked as mastered!'),
        backgroundColor: const Color(0xFF2E7D32),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: [
              // Top Bar
              _buildTopBar(),
              
              // Main Content
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // Morph Container
                    _buildMorphContainer(),
                    
                    const SizedBox(height: 20),
                    
                    // Morse Code Display
                    Text(
                      currentCharacter.morseCode,
                      style: const TextStyle(
                        fontSize: 40,
                        letterSpacing: 5,
                        fontFamily: 'monospace',
                        color: Colors.white,
                      ),
                    ),
                    
                    const SizedBox(height: 40),
                    
                    // Action Buttons
                    _buildActionButtons(),
                  ],
                ),
              ),
              
              // Bottom Navigation
              _buildBottomNavigation(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTopBar() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
          onTap: () => Navigator.pop(context),
          child: const Text(
            '← Back to Levels',
            style: TextStyle(
              color: Color(0xFF00BFFF),
              fontSize: 16,
            ),
          ),
        ),
        Text(
          'Character: ${_currentIndex + 1}/$_totalLevels',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 16,
          ),
        ),
      ],
    );
  }

  Widget _buildMorphContainer() {
    return Container(
      width: 250,
      height: 250,
      decoration: BoxDecoration(
        color: const Color(0xFF1E1E1E),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          // Character
          Text(
            currentCharacter.character,
            style: const TextStyle(
              fontSize: 150,
              fontWeight: FontWeight.bold,
              color: Color(0xFF555555),
            ),
          ),
          
          // Dynamic Morse Elements
          ..._buildMorseElements(),
        ],
      ),
    );
  }

  List<Widget> _buildMorseElements() {
    final elements = currentCharacter.elements;
    final widgets = <Widget>[];
    
    // 动态计算位置
    const double startX = 50;
    const double startY = 50;
    const double elementSpacing = 35;
    
    for (int i = 0; i < elements.length && i < _elementAnimations.length; i++) {
      final element = elements[i];
      final animation = _elementAnimations[i];
      
      final double x = startX + (i % 4) * elementSpacing;
      final double y = startY + (i ~/ 4) * 40;
      
      Widget elementWidget;
      if (element == MorseElement.dot) {
        elementWidget = Container(
          width: 20,
          height: 20,
          decoration: const BoxDecoration(
            color: Color(0xFF00BFFF),
            shape: BoxShape.circle,
          ),
        );
      } else {
        elementWidget = Container(
          width: 30,
          height: 15,
          decoration: BoxDecoration(
            color: const Color(0xFF00BFFF),
            borderRadius: BorderRadius.circular(8),
          ),
        );
      }
      
      widgets.add(
        Positioned(
          left: x,
          top: y,
          child: AnimatedBuilder(
            animation: animation,
            builder: (context, child) {
              double opacity = _hasPlayedOnce ? 1.0 : animation.value;
              return Opacity(
                opacity: opacity,
                child: Transform.scale(
                  scale: _hasPlayedOnce ? 1.0 : animation.value,
                  child: elementWidget,
                ),
              );
            },
          ),
        ),
      );
    }
    
    return widgets;
  }

  Widget _buildActionButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _buildActionButton(
          icon: Icons.skip_previous,
          onTap: _goToPrevious,
        ),
        const SizedBox(width: 20),
        _buildActionButton(
          icon: _isPlaying ? Icons.volume_up : Icons.play_arrow,
          onTap: _isPlaying ? null : _playMorseCode,
          isPlayButton: true,
        ),
        const SizedBox(width: 20),
        _buildActionButton(
          icon: Icons.skip_next,
          onTap: _goToNext,
        ),
      ],
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required VoidCallback? onTap,
    bool isPlayButton = false,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 60,
        height: 60,
        decoration: BoxDecoration(
          color: isPlayButton ? const Color(0xFF00BFFF) : const Color(0xFF1E1E1E),
          shape: BoxShape.circle,
        ),
        child: Icon(
          icon,
          size: 28,
          color: isPlayButton ? Colors.white : const Color(0xFFAAAAAA),
        ),
      ),
    );
  }

  Widget _buildBottomNavigation() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
          onTap: _goToPrevious,
          child: const Text(
            'PREV',
            style: TextStyle(
              color: Color(0xFFAAAAAA),
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        GestureDetector(
          onTap: _markAsMastered,
          child: const Text(
            'Mark as Mastered',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        GestureDetector(
          onTap: _goToNext,
          child: const Text(
            'NEXT',
            style: TextStyle(
              color: Color(0xFFAAAAAA),
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
  }
}
